import { Comment } from '@ant-design/compatible';
import { Avatar, Form, Button, List, message, Pagination } from 'antd';
import { useSelector, useDispatch } from 'react-redux';
import { IStore } from '../redux/typings';
import { UserOutlined } from '@ant-design/icons';
import { Editor } from '@toast-ui/react-editor';
import '@toast-ui/editor/dist/toastui-editor.css';
import { useRef, useState, useEffect } from 'react';
import { getIssueCommentById, getBookCommentById, postAddComment, updateCommentNum, updateBookCommentNum } from "../api/comment"
import { getUserById } from '../api/user';
import { ICommentList, IIssueInfo, IBookInfo } from "../typings"
import { formatTimestamp } from "../utils/tools"
import { updateUserInfoAsync } from "../redux/userSlice";
import styles from "../css/Discuss.module.scss"

interface IProps {
    commentType: number, //1:问答 2:书籍
    targetId: string | undefined,
    issueInfo?: IIssueInfo | undefined,
    bookInfo?: IBookInfo | undefined,
}

const Disscuss = (props: IProps) => {
    const editorRef = useRef(null);
    const dispatch = useDispatch();
    const { isLogin, userInfo } = useSelector((state: IStore) => state.user);
    const [commentList, setCommentList] = useState<ICommentList[]>([]);
    const [pageInfo, setPageInfo] = useState({
        current: 1,
        eachPage: 10,
        total: 0,
        totalPage: 0
    });
    // 根据登录状态进行头像处理
    let avatar = null;
    if (isLogin) {
        avatar = <Avatar src={userInfo.avatar} />
    } else {
        avatar = <Avatar icon={<UserOutlined />} />
    }

    const fetchData = async () => {
        let data = null;
        if (props.commentType === 1) {
            // 问答对应评论
            const res = await getIssueCommentById((props.targetId as string), {
                current: pageInfo.current,
                pageSize: pageInfo.eachPage
            })
            data = res.data.data;
        } else if (props.commentType === 2) {
            // 书籍对应的评论
            const res = await getBookCommentById((props.targetId as string), {
                current: pageInfo.current,
                pageSize: pageInfo.eachPage
            })
            data = res.data.data;
        }
        for (let i = 0; i < data.data.length; i++) {
            const result = await getUserById(data.data[i].userId);
            // 将用户信息添加到评论对象上
            data.data[i].userInfo = result.data.data;
        }
        // 更新评论数据
        setCommentList(data.data)
        // 更新分页数据
        setPageInfo({
            current: data.currentPage,
            eachPage: data.eachPage,
            total: data.count,
            totalPage: data.totalPage
        })
    }
    useEffect(() => {
        if (props.targetId) {
            fetchData();
        }
    }, [props.targetId, pageInfo.current, pageInfo.eachPage])

    // 添加评论
    const addComment = async () => {
        let value = (editorRef.current as any).getInstance().getHTML();
        if (value === "<p><br></p>") {
            value = ""
        }
        if (!value) {
            message.warning("请输入评论内容");
            return;
        }
        if (props.commentType === 1) {
            // 问答
            await postAddComment({
                userId: (userInfo as any)._id,
                typeId: props.issueInfo?.typeId as string,
                commentContent: value,
                commentType: props.commentType,
                issueId: (props.issueInfo?._id as string),
                bookId: null,
            })
            message.success("添加评论成功");
            fetchData();
            // 请空markdown编辑器
            (editorRef.current as any).getInstance().setHTML("")
            // 积分变化
            dispatch((updateUserInfoAsync as any)({
                userId: (userInfo as any)._id,
                newInfo: {
                    points: (userInfo as any).points + 4
                }
            }));
            // 更新评论数
            let num = props.issueInfo?.commentNumber as number
            updateCommentNum(props.targetId as string, {
                commentNumber: ++num,
            })
        } else {
            // 书籍
            await postAddComment({
                userId: (userInfo as any)._id,
                typeId: props.bookInfo?.typeId as string,
                commentContent: value,
                commentType: props.commentType,
                issueId: null,
                bookId: props.bookInfo?._id as string,
            })
            message.success("评论添加成功，积分+2");
            fetchData();
            // 请空markdown编辑器
            (editorRef.current as any).getInstance().setHTML("")
            // 积分变化
            dispatch((updateUserInfoAsync as any)({
                userId: (userInfo as any)._id,
                newInfo: {
                    points: (userInfo as any).points + 4
                }
            }));
            // 更新评论数
            let num = props.bookInfo?.commentNumber as number
            updateBookCommentNum(props.targetId as string, {
                commentNumber: ++num,
            })
        }
    }

    // 评论翻页
    const onChange = (current: number, pageSize: number) => {
        const info = { ...pageInfo };
        info.current = current;
        info.eachPage = pageSize;
        setPageInfo(info)
    }

    return (
        <div>
            {/* 评论框 */}
            <Comment
                avatar={avatar}
                content={
                    <>
                        <Form.Item>
                            <Editor
                                initialValue=""
                                previewStyle="vertical"
                                height="270px"
                                initialEditType="wysiwyg"
                                useCommandShortcut={true}
                                language='zh-CN'
                                ref={editorRef}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Button onClick={addComment} disabled={isLogin ? false : true} type="primary">添加评论</Button>
                        </Form.Item>
                    </>
                }
            />
            {/* 评论列表 */}
            {commentList.length > 0 ? <List header="当前评论"
                dataSource={commentList}
                renderItem={(item) => {
                    return <Comment
                        content={
                            <div dangerouslySetInnerHTML={{ __html: item.commentContent }}></div>
                        }
                        avatar={<Avatar src={item.userInfo?.avatar} />}
                        datetime={
                            <span>{formatTimestamp(item.commentDate, "YYYY-MM-DD HH:mm:ss")}</span>
                        }
                    />
                }}
            /> : <></>}
            {/* 分页 */}
            {commentList.length > 0 ? (
                <div className={styles.paginationContainer}>
                    <Pagination
                        showQuickJumper
                        defaultCurrent={1}
                        total={pageInfo.total}
                        onChange={onChange}
                    />
                </div>
            ) : <div style={{ fontWeight: "200", textAlign: "center", margin: "50px" }}>暂无评论</div>}
        </div>
    );
}

export default Disscuss;